package com.weibo.user.severlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.weibo.common.BaseSeverlet;
import com.weibo.user.User;
import com.weibo.user.service.UserService;
import com.weibo.user.service.imp.UserServiceImp;

public class MailBackServlet extends BaseSeverlet {

	private static final Logger logger = Logger
			.getLogger(MailBackServlet.class);

	@Override
	public void doService(HttpServletRequest request,
			HttpServletResponse response) {
		String registerID = request.getParameter("registerId");
		if (registerID == null) {
			try {
				request.getRequestDispatcher("/Login_business.jsp").forward(
						request, response);
			} catch (ServletException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return;
		}

		String registerName = (String) request.getSession().getAttribute(
				registerID);

		if (registerName == null || registerName.equals("")) {
			try {
				request.getRequestDispatcher("/Login_business.jsp").forward(
						request, response);
			} catch (ServletException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return;
		}
		// 将用户状态该为已经激活
		HttpSession session = request.getSession();
		UserService userService = new UserServiceImp();
		User user = userService.getUserByName((String) session
				.getAttribute(registerID));
		if (user != null) {
			user.setUser_state("yes");
			logger.info(registerName + "用户邮箱激活成功！");
			if (!userService.updateUser(user)) {
				try {
					request.getRequestDispatcher("/Login_business.jsp")
							.forward(request, response);
				} catch (ServletException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				return;
			}

			request.setAttribute("registerName", registerName);
			try {
				response.setHeader("Refresh", "5;URL=/weibo/index.jsp");
				request.getRequestDispatcher("/WEB-INF/login/Login_mail_success.jsp")
						.forward(request, response);
			} catch (ServletException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			try {
				request.getRequestDispatcher("/Login_business.jsp").forward(
						request, response);
			} catch (ServletException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}